# -*- coding: utf-8 -*-
import time
from typing import List
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_cdn20180510.client import Client as Cdn20180510Client
from alibabacloud_cdn20180510 import models as cdn_20180510_models


# Service 初始化何种服务


class Aliyun(object):
    client = None

    def __init__(self, args):
        AccessKeyId = args['AccessKeyId']
        AccessKeySecret = args['AccessKeySecret']

        config = open_api_models.Config(
            access_key_id=AccessKeyId,
            access_key_secret=AccessKeySecret
        )

        config.endpoint = f'cdn.aliyuncs.com'
        self.client = Cdn20180510Client(config)

    def cdnDomains(self, args) -> None:
        # 查询所有主域名模糊查询
        describe_user_domains_request = cdn_20180510_models.DescribeUserDomainsRequest(
            domain_name=args['domain'],
            domain_search_type='fuzzy_match',
            page_size=100
        )

        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            res = self.client.describe_user_domains_with_options(
                describe_user_domains_request, runtime)
            body = res.to_map()["body"]
            records = body["Domains"]["PageData"]
            lst = []
            for d in records:
                lst.append(d["DomainName"])
            return {"code": 200, "message": lst}
        except Exception as error:
            print(error.message)
            return {"code": error.data.get("statusCode"), "message": error.data.get("Message")}

    def sslUploadCdn(self, args) -> None:
        # 上传证书到CDN
        formatted_time = time.strftime("%Y%m%d%H%M%S",  time.localtime())
        set_cdn_domain_sslcertificate_request = cdn_20180510_models.SetCdnDomainSSLCertificateRequest(
            domain_name=args['domain'],
            cert_name=formatted_time,
            cert_id=int(formatted_time),
            cert_type='upload',
            sslprotocol='on',
            sslpub=args['sslPem'],
            sslpri=args['sslKey']
        )

        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值 如果异步在方法后面加 _async 前加 await
            self.client.set_cdn_domain_sslcertificate_with_options(
                set_cdn_domain_sslcertificate_request, runtime)
            # message 证书的名称
            return {"code": 200, "message": formatted_time}
        except Exception as error:
            print(error.message)
            return {"code": error.data.get("statusCode"), "message": error.data.get("Message")}
